<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 获取微信分享需要参数
 * Class Service
 * @package app\api\controller
 */
class ServiceController extends CommonController {

    private $appid;
    private $appsecret;
    //private $shareUrl="http://www.cdbottle.com/home/service/index?from=singlemessage&isappinstalled=0";
    //"https://www.cdbottle.com/home/service/index?from=singlemessage"

    private $shareurl = '';

    public function __construct()
    {
        parent::__construct();

        $this->appid = config('other.appid');
        $this->appsecret = config('other.appsecret');
    }

    /**
     * 生个各种参数，功前台调用
     * @param  url  需要分享的页面url地址
     */
    public function createParam(){
        //     $this->shareurl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        //    $this->shareurl = urlencode($this->params['url']);
        $this->shareurl = $this->request->input('url');
        //  $this->shareurl="http://www.cgqwhg.com/wx/";
        $this->wx_get_jsapi_ticket();
        $timestamp = (int)time();//生成签名的时间戳
        $wxnonceStr=$this->createNonceStr();//生成签名的随机串
        $wxticket = Cache::get('wx_ticket');
        $wxOri = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",$wxticket, $wxnonceStr, $timestamp,$this->shareurl);
        $wxSha1 = sha1($wxOri);// 签名

        $data =  ["timestamp"=>$timestamp,'wxnonceStr'=>$wxnonceStr,"wxticket"=>$wxticket,"wxSha1"=>$wxSha1,'appid'=>$this->appid,'url'=>$this->shareurl];
        return $this->returnApi(200,'获取成功', 'YES' , $data);
    }

    //获取随机字符串
    function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //获取token
    function wx_get_token(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret;
        $res = $this->httpGet($url);
        $res = json_decode($res,true);

        $access_token=$res['access_token'];

        Cache::put('access_token', $access_token, 3600);
    }



    //获取ticket
    function wx_get_jsapi_ticket(){
        $ticket="";
        do{
            $ticket = Cache::get('wx_ticket');
            $token = Cache::get('access_token');
            if(!empty($ticket) && !empty($token)){
                break;
            }
            $token= Cache::get('access_token');
            if(empty($token)){
                $this->wx_get_token();
            }
            $token= Cache::get('access_token');

            if(empty($token)){
                Log::error("get access token error.");
                break;
            }

            $url=sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$token&type=jsapi",
                $token);
            $res=$this->httpGet($url);
            $res=json_decode($res,true);
            $ticket=$res['ticket'];

            Cache::put('wx_ticket',$ticket,3600);
        }while(0);
        return $ticket;
    }

    //curl   get请求
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }



    //curl-post请求信息
    public function request($isbn='',$params=array()){
        header("content-type:text/html;charset=utf-8");
        $url = 'https://api.douban.com/v2/book/isbn/'.$isbn;
        $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_COOKIEJAR, $this->ckfile);
        // curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //curl_setopt($ch, CURLOPT2_USERAGENT, $useragent);
        // curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
        if(!empty($params)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
    }
}